package org.csu.mypetstore.web.servlets;

import org.csu.mypetstore.domain.Account;
import org.csu.mypetstore.domain.Cart;
import org.csu.mypetstore.domain.Item;
import org.csu.mypetstore.service.CartService;
import org.csu.mypetstore.service.CatalogService;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;

public class AddItemToCartServlet extends HttpServlet {

    //1.处理完请求后的跳转页面
    private static final String VIEW_CART = "/WEB-INF/jsp/cart/Cart.jsp";
    private static final String ERROR = "/WEB-INF/jsp/common/Error.jsp";
    //2.定义处理该请求所需要的数据
    private String workingItemId;//所添加的商品id
    private Cart cart;//购物车。不能直接在这里new出来，要放到session里，以便用户使用过程中多次访问它
    //3.是否需要调用业务逻辑层
    private CatalogService catalogService;
    private CartService cartService;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        workingItemId = request.getParameter("workingItemId");

        HttpSession session = request.getSession();
        if(session.getAttribute("account")==null)
        {
            session.setAttribute("message","Please Sign In At First!");
            request.getRequestDispatcher(ERROR).forward(request,response);
            return;
        }
        cartService = new CartService();
        cart = (Cart) session.getAttribute("cart");//将Object强制转换成Cart

        if(cart == null){
            cart = new Cart();
        }

        //有bug，刷新就会一直加，应该像移除那样判断一下是否选中！！（改天搞个flag变量）
        if(cart.containsItemId(workingItemId)){
            cart.incrementQuantityByItemId(workingItemId);

            if(session.getAttribute("account")!=null)
            {
                Account account = (Account)session.getAttribute("account");
                cartService.incrementQuantityByItemId(account.getUsername(),workingItemId);
            }

        }else {
            catalogService = new CatalogService();
            boolean isInStock = catalogService.isItemInStock(workingItemId);//库存是否够
            Item item = catalogService.getItem(workingItemId);
            cart.addItem(item,isInStock);

            if(session.getAttribute("account")!=null)
            {
                Account account = (Account) session.getAttribute("account");
                cartService.addItem(account.getUsername(),workingItemId);
            }
        }

        session.setAttribute("cart",cart);
        request.getRequestDispatcher(VIEW_CART).forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }
}
